package com.tyut.farmerservice.inteceptor;

import com.tyut.farmerservice.config.BaseContext;
import com.tyut.farmerservice.config.JWTConfig;
import com.tyut.farmerservice.util.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    @Resource
    private JWTConfig jwtConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        // 检验JWT令牌，没有则不放行
        String token = request.getHeader(jwtConfig.getUserTokenName());
        try {
            Claims claims = JWTUtils.parseJWT(jwtConfig.getUserSecretKey(), token);
            String username = claims.getSubject();
            log.info("当前用户为：{}", username);
            BaseContext.setCurrentId(username);
            // 通过 放行
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setStatus(403);
            return false;
        }
    }
}
